﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using OBDUDSUtils.Common;

namespace DeviceTestStand
{
    public partial class FrmScriptManager : Form
    {
        private const string PLATFORM_DIR = "data";
        private string platformDataFile;
        private string currentSelectScript;

        public FrmScriptManager()
        {
            InitializeComponent();
        }

        private void FrmScriptManager_Load(object sender, EventArgs e)
        {
            Init();

            EventHandlers();
        }

        private void EventHandlers()
        {
            this.btn_add.Click += Btn_add_Click;
            this.btn_clearMsg.Click += Btn_clearMsg_Click;
            this.btn_delete.Click += Btn_delete_Click;
            this.btn_clearView.Click += Btn_clearView_Click;
            this.btn_exit.Click += Btn_exit_Click;
            this.btn_insert.Click += Btn_insert_Click;
            this.btn_save.Click += Btn_save_Click;
            this.btn_saveExit.Click += Btn_saveExit_Click;

            this.btn_addScript.Click += Btn_addScript_Click;
            this.btn_editScript.Click += Btn_editScript_Click;
            this.btn_delScript.Click += Btn_delScript_Click;
            this.btn_delAllScript.Click += Btn_delAllScript_Click;

            this.lv_script.TabIndexChanged += Lv_script_TabIndexChanged;
        }

        private void Lv_script_TabIndexChanged(object sender, EventArgs e)
        {
            if (this.uiTabControlMenu1.SelectedTab == this.tabPage1)
            {
                RefreshScript();
            }
        }

        private void Btn_delAllScript_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show($"确认要删除所有脚本？", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) != DialogResult.Yes)
                return;
            var scriptfile = System.Environment.CurrentDirectory + "\\data\\";
            Directory.Delete(scriptfile, true);
        }

        private void Btn_delScript_Click(object sender, EventArgs e)
        {
            var scriptfile = System.Environment.CurrentDirectory + "\\data\\";
            var script = this.lv_script.FocusedItem.Text;
            if (MessageBox.Show($"确认要删除脚本{script}？", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) != DialogResult.Yes)
                return;
            File.Delete(scriptfile + script);
        }

        private void Btn_editScript_Click(object sender, EventArgs e)
        {
            if (this.lv_script.FocusedItem == null)
            {
                MessageBox.Show("请选择要编辑的脚本！");
                return;
            }
            this.tb_scriptName.Text = this.lv_script.FocusedItem.Text;
            //update content
            this.lv_messages.Items.Clear();
            foreach (var script in UpdatePlatform.ReadScriptMessage(System.Environment.CurrentDirectory + "\\data\\" + this.tb_scriptName.Text))
            {
                this.lv_messages.Items.Add(new ListViewItem(script));
            }
            this.uiTabControlMenu1.SelectedTab = this.tabPage2;
        }

        private void Btn_addScript_Click(object sender, EventArgs e)
        {
            this.tb_scriptName.Text = String.Empty;
            this.lv_messages.Items.Clear();
            this.uiTabControlMenu1.SelectedTab = this.tabPage2;
        }

        private void Btn_saveExit_Click(object sender, EventArgs e)
        {
            if (this.tb_scriptName.Text.Trim() == "")
            {
                MessageBox.Show("脚本名称不能为空！");
                return;
            }
            if (!Directory.Exists(this.platformDataFile))
                Directory.CreateDirectory(this.platformDataFile);
            if (!SaveFile(this.platformDataFile + "\\" + this.tb_scriptName.Text.Trim()))
                return;
            this.Close();
        }

        private void Btn_save_Click(object sender, EventArgs e)
        {
            if (this.tb_scriptName.Text.Trim() == "")
            {
                MessageBox.Show("脚本名称不能为空！");
                return;
            }
            if (!Directory.Exists(this.platformDataFile))
                Directory.CreateDirectory(this.platformDataFile);

            if (!SaveFile(this.platformDataFile + "\\" + this.tb_scriptName.Text.Trim()))
                return;
            MessageBox.Show("保存成功！");
        }

        private void Btn_insert_Click(object sender, EventArgs e)
        {
            if (this.lv_messages.FocusedItem.Text.Trim() == "")
            {
                MessageBox.Show("请选择插入的位置！");
                return;
            }
            int index = this.lv_messages.FocusedItem.Index;
            string result;
            if (!IsCommandLegal(this.tb_message.Text, out result))
                return;

            ListViewItem lv = new ListViewItem(result);
            if (index > 0)
            {
                this.lv_messages.Items.Insert(index, lv);
            }
            else
            {
                this.lv_messages.Items.Add(lv);
            }
        }

        private void Btn_exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Btn_clearView_Click(object sender, EventArgs e)
        {
            this.lv_messages.Items.Clear();
        }

        private void Btn_delete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show($"确认要删除指令：{this.lv_messages.FocusedItem.Text}？", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) != DialogResult.Yes)
                return;
            this.lv_messages.FocusedItem.Remove();
        }

        private void Btn_clearMsg_Click(object sender, EventArgs e)
        {
            this.tb_message.Clear();
        }

        private void Btn_add_Click(object sender, EventArgs e)
        {
            var message = this.tb_message.Text.Trim();
            string result;
            if (!IsCommandLegal(message, out result))
                return;

            ListViewItem lv = new ListViewItem(result);
            this.lv_messages.Items.Add(lv);
        }

        private void Init()
        {
            this.lv_messages.View = View.Details;
            this.lv_messages.FullRowSelect = true;
            this.lv_messages.HeaderStyle = ColumnHeaderStyle.None;
            this.lv_messages.Columns.Add("", this.lv_messages.Width - 30, HorizontalAlignment.Center);

            this.lv_script.View = View.Details;
            this.lv_script.FullRowSelect = true;
            this.lv_script.HeaderStyle = ColumnHeaderStyle.None;
            this.lv_script.Columns.Add("", this.lv_script.Width - 30, HorizontalAlignment.Center);

            this.platformDataFile = System.Environment.CurrentDirectory + "\\" + PLATFORM_DIR + "\\";
            if (!Directory.Exists(this.platformDataFile))
                Directory.CreateDirectory(this.platformDataFile);

            this.tb_scriptName.Text = "pl001_" + System.DateTime.Now.ToString("yyyyMMddHHmmss");

            RefreshScript();
        }

        private void RefreshScript()
        {       
            //update script file
            var script = System.Environment.CurrentDirectory + "\\data\\";
            foreach (var file in new DirectoryInfo(script).GetFiles())
            {
                ListViewItem lv = new ListViewItem(file.Name);
                this.lv_script.Items.Add(lv);
            }
            if (this.lv_script.Items.Count > 0)
            {
                this.lv_script.FocusedItem = this.lv_script.Items[0];
            }
        }

        private bool IsCommandLegal(string message, out string result)
        {
            var cmdArray = message.Split(' ');
            if (cmdArray.Length < 1)
            {
                result = message;
                MessageBox.Show("长度不足!");
                return false;
            }
            //验证是否是有效十六进制数
            foreach (var hex in cmdArray)
            {
                try
                {
                    Convert.ToInt32(hex.Trim(), 16);
                }
                catch (Exception ex)
                {
                    result = message;
                    MessageBox.Show("数据包含非法字符！请输入有效十六进制数据！");
                    return false;
                }
            }

            if (cmdArray.Length < 8)//填充剩余长度
            {
                for (int i = 0; i < 8 - cmdArray.Length; i++)
                {
                    message += " 00";
                }
                result = message;
                return true;
            }
            else if (cmdArray.Length > 8)//截取有效8位长度
            {
                message = "";
                for (int i = 0; i < 8; i++)
                {
                    message += cmdArray[i] + " ";
                }
                result = message;
                return true;
            }

            result = message;
            return true;
        }

        private bool SaveFile(string filePath)
        {
            if (this.lv_messages.Items.Count <= 0)
            {
                MessageBox.Show("没有可以保存的数据！");
                return false;
            }
            //新增保存时判断脚本是否存在
            if (!IsExistScript(this.tb_scriptName.Text.Trim()))
                return false;

            StringBuilder buffer = new StringBuilder();
            foreach (ListViewItem lv in this.lv_messages.Items)
            {
                buffer.AppendLine(lv.SubItems[0].Text.Trim());
            }

            using (FileStream fs = new FileStream(filePath, FileMode.Create))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.WriteLine(buffer);
                }
            }

            return true;
        }

        private bool IsExistScript(string scriptName)
        {
            var scriptfile = System.Environment.CurrentDirectory + "\\data\\";
            foreach (var script in new DirectoryInfo(scriptfile).GetFiles())
            {
                if (script.Name.Trim() == scriptName)
                    return true;
            }
            return false;
        }
    }
}
